package com.util;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description ZookeeperClient，可以与distributed-server统一抽取到一个项目中提供注册和发现的功能
 * @author TDW
 * @date 2018年6月8日
 *
 */
public class ZookeeperClient {

	private static final Logger logger = LoggerFactory.getLogger(ZookeeperClient.class);
	private static final Integer TIME_OUT = 2000;
//	private static final String ZOOKEEPER_CONNECTION_HOST = "192.168.1.232:2181,192.168.1.232:2182,192.168.1.232:2183";
	private static final String ZOOKEEPER_CONNECTION_HOST = "192.168.1.126:2181";
	/**
	 * key-value:<br>
	 * key: host:port/serverName<br>
	 * value: server session size
	 */
	public static ConcurrentHashMap<String, Integer> serverMap = null;
	
	/**
	 * server node :<br>
	 * node, node data: host:port/serverName#sessionSize
	 */
	private static final String SERVER_PARENT_NODE = "/servers";
	
	public static ZooKeeper zkClient = null;
	/**
	 * init 
	 */
	static{
		try {
			zkClient = new ZooKeeper(ZOOKEEPER_CONNECTION_HOST, TIME_OUT, new Watcher() {
				
				@Override
				public void process(WatchedEvent arg0) {
					getServerHost();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @description getServerHost
	 * @return
	 * @author TDW
	 * @date 2018年6月8日
	 * @modify_date 
	 * @modify_author
	 * @modify_desc
	 */
	public static ConcurrentHashMap<String, Integer> getServerHost() {
		ConcurrentHashMap<String,Integer> tempMap = null;
		try {
			List<String> zkNodeList = zkClient.getChildren(SERVER_PARENT_NODE, false);
			tempMap = new ConcurrentHashMap<String,Integer>();
			//node data: host:port/serverName#sessionSize
			String serverHost = null;
			Integer sessionSize = 0;
			String zkNodeData = null;
			for(String zkNode : zkNodeList){
				zkNodeData = new String(zkClient.getData(SERVER_PARENT_NODE+"/"+zkNode, false, null));
				serverHost = zkNodeData.split("#")[0];
				sessionSize = Integer.parseInt(zkNodeData.split("#")[1]);
				tempMap.put(serverHost, sessionSize);
			}
			serverMap = tempMap;
			logger.info("######服务端可用的server列表"+serverMap);
		} catch (Exception e) {
			logger.error("获取服务器失败",e);
		}
		return tempMap;
	}

}
